#!/usr/bin/env python3
"""Check if OrderTemplate.java invokes getSupplierInfo function"""

import pickle
import networkx as nx
from neo4j import GraphDatabase

# Load the original graph
print("Loading original graph...")
with open('business-payout.pkl', 'rb') as f:
    G = pickle.load(f)

source_file = 'business-payout-biz/src/main/java/com/pingpongx/business/payout/biz/service/core/OrderTemplate.java'
target_function = 'getSupplierInfo'

print(f"\n=== Checking in NetworkX Graph ===")
print(f"Source: {source_file}")
print(f"Looking for invocations of: {target_function}")

# Check all outgoing edges from OrderTemplate.java
if source_file in G:
    out_edges = list(G.out_edges(source_file, data=True))

    # Filter for invokes relationships
    invokes_edges = []
    for source, target, data in out_edges:
        if data.get('type') == 'invokes':
            invokes_edges.append((source, target, data))

    print(f"\nTotal outgoing 'invokes' edges: {len(invokes_edges)}")

    # Check if any target contains getSupplierInfo
    found_supplier_info = []
    for source, target, data in invokes_edges:
        if target_function in target:
            found_supplier_info.append(target)

    if found_supplier_info:
        print(f"\n✅ Found {len(found_supplier_info)} invocations of {target_function}:")
        for target in found_supplier_info:
            print(f"  -> {target}")
    else:
        print(f"\n❌ No invocations of {target_function} found")

    # Show all invokes targets for reference
    if invokes_edges:
        print(f"\nAll functions invoked by this file:")
        for source, target, data in invokes_edges[:10]:  # Show first 10
            print(f"  -> {target}")
        if len(invokes_edges) > 10:
            print(f"  ... and {len(invokes_edges)-10} more")
else:
    print(f"Source file not found in graph!")

# Check in Neo4j
print(f"\n=== Checking in Neo4j Database ===")

driver = GraphDatabase.driver("bolt://localhost:5018", auth=("neo4j", "neo4j123"))

with driver.session() as session:
    # Check for INVOKES relationships
    result = session.run("""
        MATCH (source:Node {id: $source_id})-[:INVOKES]->(target:Node)
        WHERE target.id CONTAINS $function_name
        RETURN target.id, target.type
    """, source_id=source_file, function_name=target_function)

    records = list(result)
    if records:
        print(f"\n✅ Found {len(records)} invocations of {target_function}:")
        for record in records:
            print(f"  -> {record['target.id']} (type: {record['target.type']})")
    else:
        print(f"\n❌ No invocations of {target_function} found in Neo4j")

    # Show total INVOKES count
    result = session.run("""
        MATCH (source:Node {id: $source_id})-[:INVOKES]->(target:Node)
        RETURN count(*) as count
    """, source_id=source_file)

    invokes_count = result.single()['count']
    print(f"\nTotal INVOKES relationships from this file: {invokes_count}")

    # Show sample of invoked functions
    result = session.run("""
        MATCH (source:Node {id: $source_id})-[:INVOKES]->(target:Node)
        RETURN target.id, target.type
        LIMIT 10
    """, source_id=source_file)

    print(f"\nSample of invoked functions:")
    for record in result:
        print(f"  -> {record['target.id']} (type: {record['target.type']})")

driver.close()

print("\n=== Summary ===")
print(f"Checked for invocations of '{target_function}' from OrderTemplate.java")
print("Note: The graph only shows direct invocations captured during parsing.")